package com.golxen.framework.db;


import com.alibaba.druid.pool.DruidDataSource;
import com.golxen.framework.common.BuiltinPlugin;
import com.golxen.utils.LogUtil;
import com.golxen.utils.YmlUtil;
import com.mysql.cj.util.LogUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit;

/**
 * 数据库类连接池配置
 */
public class DruidDBPool implements IDBPool {
	DruidDataSource druidDataSource;

	public DruidDBPool(String url,String user,String password){
		druidDataSource = new DruidDataSource();
		//数据源连接参数配置
		try {
			druidDataSource.setDriverClassName(YmlUtil.getString("dbConfig.driver-class-name"));
			druidDataSource.setUrl(url);
			druidDataSource.setUsername(user);
			druidDataSource.setPassword(password);
			//连接池参数设置
			druidDataSource.setMinIdle(YmlUtil.getInt("dbConfig.min-idle"));
			druidDataSource.setMaxActive(YmlUtil.getInt("dbConfig.maxActive"));
			druidDataSource.setTimeBetweenEvictionRunsMillis(YmlUtil.getLong("dbConfig.timeBetweenEvictionRunsMillis"));
			druidDataSource.setMinEvictableIdleTimeMillis(YmlUtil.getLong("dbConfig.minEvictableIdleTimeMillis"));
			druidDataSource.setValidationQuery(YmlUtil.getString("dbConfig.validationQuery"));
			druidDataSource.setTestWhileIdle(YmlUtil.getBoolean("dbConfig.testWhileIdle"));
			druidDataSource.setTestOnBorrow(YmlUtil.getBoolean("dbConfig.testOnBorrow"));
			druidDataSource.setTestOnReturn(YmlUtil.getBoolean("dbConfig.testOnReturn"));

			System.out.println(druidDataSource.getName());
		} catch (Exception e) {
			LogUtil.DB.error(e.getMessage(), e);
		}
	}


	@Override
	public void shutdown() {
		if (druidDataSource != null) {
			druidDataSource.close();
		}
	}

	@Override
	public Connection getConnection() {
		try {
			Connection conn;
			conn = druidDataSource.getConnection();
			return conn;
		} catch (SQLException e) {
			LogUtil.DB.error(druidDataSource.getName(), e);
		}
		return null;
	}

}
